package com.hzit.manager.controller;

import com.hzit.common.util.R;
import com.hzit.manager.client.UserClient;
import com.hzit.manager.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.jnlp.UnavailableServiceException;

/**
 * 类名：
 * 作者：WF
 * 功能：@LoadBalanced注解，可以通过服务名字直接访问微服务，此时千万不要在控制层注入LoadBalancerClient组件，否则，冲突报：no instances ...
 * @Bean
 * @LoadBalanced   //不要添加此注解，因为在控制层中己注入了负载均衡组件,如果使用了它就不要在控制层使用LoadBalancerClient
 * 	public RestTemplate restTemplate(){
 * 		return new RestTemplate();
 * }
 */

@RestController
@RequestMapping("/rest2")
@Slf4j
public class RestTemplateController2 {
	@Autowired
	private RestTemplate restTemplate;
	private static final String USER_SERVICE = "hzit-user";

	@Autowired
	private UserClient userClient;

	//1. 查询所有用户列表 (restTemplate来调用远程服务)
	@GetMapping("/user/list")
	public R findUsers(){
		ResponseEntity<R> exchange = restTemplate.exchange("http://" + USER_SERVICE + "/user/list", HttpMethod.GET, null, R.class);
		return exchange.getBody();
	}

	//2. 查询 (restTemplate来调用远程服务)
	@GetMapping("/user/findById")
	public R findUserbyId(){
		R user = restTemplate.getForObject("http://" + USER_SERVICE  + "/user/findById", R.class);
		return user;
	}

	//3. 查询单个用户(openFeign调用实现)
	@GetMapping("/user/findById2")
	public R findByUser2(Integer id){
		return userClient.findById2(id);
	}

	//4. 查询单个用户(openFeign调用实现)
	@GetMapping("/user/findById3/{id}")
	public R findByUser3(@PathVariable Integer id){
		return userClient.findById3(id);
	}
}
